<template>
	<view class="content">
		<scroll-view class="chat" scroll-y="true" scroll-with-animation="true" :scroll-into-view="scrollToView" 	>
			<view class="chat-main">
				<view class="chat-ls" v-for="(item,index) in msgs" :key="index" :id="'msg'+item.tip">
					<view class="chat-time">{{handleTime(item.time)}}</view>
					<view class="msg-m msg-left" v-if="item.id !='b'">
						<image :src="item.imgurl" class="user-img"></image>
						<view class="message">
							<view class="msg-text"> {{item.message}}
							</view>
						</view>
						
					</view>
					<view class="msg-m msg-right" v-if="item.id =='b'">
						<image :src="item.imgurl" class="user-img"></image>
						<view class="message">
							<view class="msg-text"> {{item.message}}
							</view>
						</view>
						
					</view>
				</view>
			</view>
			
		</scroll-view>
		<view class="submit">
			<view class="submit-chat">
				<textarea auto-height="true" class="chat-send btn" @input="inputs"  v-model="message"></textarea>
				<view class="bt-img" @click="sendmsg" >
					<image src="../../../static/th.jpg"></image>
				</view>
				
			</view>
		</view>
	</view>
	
</template>

<script>
	  import {mapState,mapMutations} from 'vuex';
	   import request from "../../../request/request.js";
	   import uParse  from "../../../components/feng-parse/parse.vue"; 
	export default {
		data(){
			return{
				message:"",
				scrollToView:"",
				msgs:[
					{
						id:'a',
						imgurl:"../../../static/wxlogo.png",
						message:"sdsdsda",
						types:0,
						tip:0,
						time:new Date() -1000
					},
				]
			}
		},
		components:{
			uParse ,  
		},
		onLoad() {
			this.init();
		},
      computed:{
      ...mapState('m_user',['userinfo'])
       },
		methods:{
				navigate(href, e) {
				    }
,
			pushmsg(id,msg){	
				let len=this.msgs.length;
				let data={
						id:id,
						imgurl:this.userinfo.headImage,
						message:msg,
						types:0,
						tip:len,
						time:new Date()
				}
					
				if(data.id==='a'){
					data.imgurl="../../../static/wxlogo.png";
				}
				this.msgs.push(data);
				// setTimeout(()=>{
					this.message="";
				// },0);
				this.$nextTick(()=>{
					this.scrollToView='msg'+len;
				});
			},
			sendmsg(){
					if(this.userinfo===""){
						uni.showToast({
							title: '请登录',
							icon: 'error',
							duration: 2000
						});
						return ;
					}
					let msgs=this.message;
					this.pushmsg('b',msgs);
					request('', '/ai/check', 'GET', "", {}).then(res => {
						// console.log("首次聊天返回结果",res)
						if (res.code === '200') {
							uni.request({
									  url: 'http://43.153.112.145:8080/api/chat/streamChatWithWeb/V3',
									  method: 'POST',
									  header: {
									    'content-type': 'application/json',
										'blueCat_token': '1660585647703904257',
										'Origin': 'http://www.chosen1.xyz',
										'Referer': 'http://www.chosen1.xyz/'
									  },
									  data:{"conversationId":"1684749412672","prompt":msgs,
									  "options":{"conversationId":"","parentMessageId":""},
									  "serviceType":"chat_gpt_model4"},
							  success:res=>{
							    
							    let stream = res.data;
								this.pushmsg('a',stream);
									   let data2={
									   	userId:this.userinfo.id,	
									   	askquestion:msgs,
									   	answerContent:stream
									   }
								  request('', '/detail/insert', 'POST', data2, {}).then(res => {
								  	// console.log("首次聊天返回结果",res)
								  	if (res.code != 200) {
								  	    // this.pushmsg('a',res.data);
								  		uni.showToast({
								  			title: res.msg,
								  			icon: 'error',
								  			duration: 2000
								  		});
								  	}
								  	uni.hideLoading();
								  }
								  )
							  }
							});
						}else{
									uni.showToast({
										title:res.msg,
										icon: 'error',
										duration: 2000
									});
						}
					}
					);
			
			
	
			},
			// sendmsg(){
			// 	if(this.userinfo===""){
			// 		uni.showToast({
			// 			title: '请登录',
			// 			icon: 'error',
			// 			duration: 2000
			// 		});
			// 		return ;
			// 	}
			// 	let msgs=this.message;
			// 	this.pushmsg('b',msgs);
			// 	// console.log("首次聊天返回结果",this.userinfo)
			
			// uni.request({
			//   url: 'https://chatmindai.aabiji.com/api4/chat-process',
			//   method: 'POST',
			//   responseType: 'arraybuffer',
			//   header: {
			//     'content-type': 'application/json',
			// 	'Authorization': 'Bearer 18073515059'
			//   },
			// 	data:{"phonenum":"18073515059","prompt":msgs,
			// 	"options":{"parentMessageId":"chatcmpl-7DT4vpi3vaM8kcYDBuRrh6l3Iwh9M"},
			// 	"template":1,"viplevel":"0"},
			//   success:res=>{
			//     const decoder = new TextDecoder('utf-8');
			//     let stream = res.data;
			//     let offset = 0;
			//    async function readChunk() {
			//      const lenBuf = new Uint8Array(stream.slice(offset, offset + 4));
			//      offset += 4;
			//      const len = new DataView(lenBuf.buffer).getUint32(0);
			//      const chunk = stream.slice(offset, offset + len);
			//      offset += len;
			//      const result = decoder.decode(new Uint8Array(chunk));
				 
			// 	const result1=result.substring(result.lastIndexOf("text")+7,result.lastIndexOf("delta"));
			// 	 const jieg=result1.substring(0,result1.lastIndexOf("delta")-3);
			// 		stream=jieg;
					
			// 	// console.info(stream)
			//      // if (offset < stream.byteLength) {
			//      //   // await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟延迟
			//      //   readChunk();
			//      // }
			//    }
			//    readChunk();
			//    let data2={
			//    	userId:this.userinfo.id,	
			//    	askquestion:msgs,
			//    	answerContent:stream
			//    }
			//    this.pushmsg('a',stream);
			//    // console.info(data2+"--------------------------");
			//   request('', '/detail/insert', 'POST', data2, {}).then(res => {
			//   	// console.log("首次聊天返回结果",res)
			//   	if (res.code != 200) {
			//   	    // this.pushmsg('a',res.data);
			//   		uni.showToast({
			//   			title: res.msg,
			//   			icon: 'error',
			//   			duration: 2000
			//   		});
			//   	}
			//   	uni.hideLoading();
			//   }
			//   )
			//   }
			// });
			 	
			// },
			inputs:function(e){
				var chatm=e.detail.value;
				var pos=chatm.indexOf('\n');
				if(pos!=-1&& chatm.length>1){
					this.sendmsg();
				}
				
			},
			init(){
				
				this.$nextTick(function(){
					this.scrollToView='msg'+this.msgs[this.msgs.length-1].tip;
				});
			},
			spaceTime(old,now){
			        old = new Date(old);
			        now = new Date(now);
			        var told = old.getTime();
			        var tnow = now.getTime();
			        if(told > (tnow+1000*60*5)){
			            return now;
			        }else{
			            return '';
			        }
			    },
			handleTime(e){
				        let old = new Date(e);
				        let now = new Date();
				        //获取old具体时间
				        let d = old.getTime();
				        let h = old.getHours();
				        let m = old.getMinutes();
				        let Y = old.getFullYear();
				        let M = old.getMonth()+1;
				        let D = old.getDate();
				        //获取now具体时间
				        let nd =now.getTime();
				        let nh = now.getHours();
				        let n = now.getMinutes();
				        let nY = now.getFullYear();
				        let nM = now.getMonth()+1;
				        let nD = now.getDate();
				         
				        //当天的时间
				        if(D === nD && M === nM && Y === nY){
				            if(h<10){
				                h = '0'+h;
				            }
				            if(m<10){
				                m = '0'+m;
				            }
				            return h+':'+m;
				        }
				        //昨天时间
				        if(D+1 === nD && M === nM && Y === nY){
				            if(h<10){
				                h = '0'+h;
				            }
				            if(m<10){
				                m = '0'+m;
				            }
				            return '昨天 '+h+':'+m;
				        }else if( Y == nY){
				            //今年
				            if(h<10){
				                h = '0'+h;
				            }
				            if(m<10){
				                m = '0'+m;
				            }
				            return M+'月'+D+'日 '+h+':'+m
				        }else{
				            //大于今年
				            if(h<10){
				                h = '0'+h;
				            }
				            if(m<10){
				                m = '0'+m;
				            }
				            return Y+'年'+ M +'月' +D+ '日 '+h+':'+m
				        }
			}
		}
	}

</script>

<style lang="scss">

@import url("../../../components/feng-parse/parse.css");	
	.submit{
		background-color: rgba(244, 244, 244, 0.96);
		border-top: 1px solid blue;
		width: 100%;
		// height: 100rpx;
		
		position: fixed;
		bottom: 0;
		z-index: 100;
		// padding-bottom: var(--status-bar-height);
	}
	.submit-chat{
		width: 100%;
		// height: 100rpx;
		display: flex;
		align-items: flex-end;
		box-sizing: border-box;
		padding: 14rpx 10rpx;
		image{
			width: 112rpx;
			height: 56rpx;
			margin: 0 10rpx;
			flex: auto;
		}
		.btn{
			// padding: 20rpx;
			flex: auto;
			background-color: #fff;
			border-radius: 10rpx;
			height: 70rpx !important; 
			// height: 100rpx;
			max-height: 160rpx;
			margin: 0 10rpx;
		}
	}
	.content{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.chat{
		// height: 100%;
		height:calc(100vh - 20rpx);//解决scroll-view固定高度问题
		.chat-main{
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-top: 100rpx;
			padding-bottom: 120rpx;
			display: flex;
			flex-direction: column;
		}
		.chat-ls{
			.chat-time{
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				line-height: 34rpx;
				padding: 20rpx 0;
				text-align: center;
			}
			.msg-m{
				display: flex;
				padding: 20rpx 0;
					
				.user-img{
					flex: none;
					width: 80rpx;
					height: 80rpx;
					border-radius: 20rpx;
				}
					
				.message{
					flex: none;
					max-width: 480rpx;
          color: #4169E1;
				}
				.msg-text{
					font-size: 32rpx;
					color: rgba(39,40,50,1);
					line-height: 44rpx;
					padding: 18rpx 24rpx;
				}
				// .msg-image{
				// 	max-width: 400rpx;
				// 	border-radius: 20rpx;
				// }
			}
			.msg-left{
				flex-direction: row;
					
				.msg-text{
					margin-left: 16rpx;
					background-color: whitesmoke;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
				}
				// .msg-image{
				// 	margin-left: 16rpx;
				// }
			}
			.msg-right{
				flex-direction: row-reverse;					
				.msg-text{
					margin-right: 16rpx;
					background-color: #55aaff;
					border-radius: 20rpx 0rpx 20rpx 20rpx;
				}
				// .msg-image{
				// 	margin-right: 16rpx;
				// }
			}
		}
	}
</style>

